package com.chat.admin.init;

import com.chat.admin.utils.RedisUtil;
import com.chat.common.common.constant.RedisKeyConstant;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * 用于初始化数据
 */
@Service
@EnableAsync
@Slf4j
public class InitService {

    @Autowired
    private RedisUtil redisUtil;

    @PostConstruct
    public void init() {
        initAsyncOnlineUserSet();
    }

    /**
     * 初始化用户的在线列表
     */
    @Async
    public void initAsyncOnlineUserSet() {
        log.info("初始化用户的在线列表");

        // 先清空原有的在线用户列表
        redisUtil.delete(RedisKeyConstant.ONLINE_USERS_SET_KEY);
        log.info("原有的在线用户列表已清空");

        Set<String> keys = redisUtil.keys(RedisKeyConstant.USER_ACCOUNT_ForToken + "*");
        if (keys.isEmpty()) {
            log.info("没有在线用户,初始化用户的在线列表完成");
            return;
        }
        Set<String> onlineAccounts = new HashSet<>();
        for (String key : keys) {
            //将User:UserAccount:ForToken:转成""
            String account = key.replace(RedisKeyConstant.USER_ACCOUNT_ForToken, "");
            onlineAccounts.add(account);
        }
        //Set<String>对象转换为一个String数组并存入redis中
        redisUtil.sAdd(RedisKeyConstant.ONLINE_USERS_SET_KEY, onlineAccounts.toArray(new String[0]));
        log.info("初始化用户的在线列表完成");
    }
}